package yunhe.servlet;

import org.json.JSONArray;
import yunhe.biz.StorageBiz;
import yunhe.biz.impl.StorageBizImpl;
import yunhe.entity.Storage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


@WebServlet(name="StorageServlet",urlPatterns="/StorageServlet")
public class StorageServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		StorageBiz stoBiz=new StorageBizImpl();
		//当前页(字符串)
		String pageIndex=req.getParameter("pageIndex");
		if(pageIndex==null){
			pageIndex="1";
		}
		//当前页（转换int）
		int curPage=Integer.parseInt(pageIndex);
		//总条数
		int stoCount=stoBiz.getStoCount();
		//每页显示行数
		int pageSize=10;
		//页数
		int totalPages=stoCount%pageSize==0?stoCount/pageSize:stoCount/pageSize+1;
		if(curPage<1){
			curPage=1;
		}else if(curPage>totalPages){
			curPage=totalPages;
		}
		String search=req.getParameter("search");
		String searchText=req.getParameter("searchText");
		HashMap<String,String> searchMap=new HashMap<>();
		searchMap.put("search", search);
		searchMap.put("searchText", searchText);
		ArrayList<Storage> stoList=stoBiz.getAllStorage(searchMap);
		
		JSONArray jsonArray=new JSONArray();
		if(!stoList.isEmpty()){
	         for (int i=0;i<stoList.size();i++){
	             Map<String,String> mss=new HashMap<String,String>();
	             mss.put("stoId",stoList.get(i).getStoId());
	             mss.put("stoName",stoList.get(i).getStoName());
	             mss.put("empName",stoList.get(i).getEmpMsg().getName());
	             mss.put("stoAddr",stoList.get(i).getStoAddr());
	             mss.put("isDefaultSto",stoList.get(i).getIsDefaultSto()+"");
	             mss.put("stoPs",stoList.get(i).getStoPs());
	             jsonArray.put(mss);
	         }
	     }
		String str="{\"total\":"+stoCount+",\"rows\":"+jsonArray.toString()+"}";
		resp.getWriter().print(str);
		
//		req.setAttribute("stoList", stoList);
//		req.setAttribute("curPage", curPage);
//		req.setAttribute("totalPages", totalPages);
//		req.getRequestDispatcher("/FileMgr/StorageFile.jsp").forward(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
